<?php
// +----------------------------------------------------------------------
// | B5LaravelCMF
// +----------------------------------------------------------------------
// | Author: 李恒 <357145480@qq.com>
// +----------------------------------------------------------------------
namespace App\Validates;


use App\Services\StructService;

class StructValidate extends ValidateBase
{
    public function rules()
    {
        return [
            'name' => 'required|min:2|max:30',
            'listsort' => 'integer'
        ];
    }

    public function attributes()
    {
        return [
            'name' => '组织名称',
            'listsort' => '显示顺序'
        ];
    }

    /**
     * 验证父级不能为自己或子类
     * @return ValidateBase
     */
    public function after_validate()
    {
        if (empty($this->error)) {
            if ($this->type == 'edit' && $this->data['id'] == $this->data['parent_id']) {
                $this->error = '上级组织不能为自己';
            } else {
                $levelsArr = [0];
                if ($this->data['parent_id'] > 0) {
                    $service = new StructService();
                    $parentInfo = $service->info($this->data['parent_id'], true);
                    if ($parentInfo) {
                        $levelsArr = explode(',', $parentInfo['levels']);
                        if ($this->type == 'edit' && in_array($this->data['id'], $levelsArr)) {
                            $this->error = '上级组织不能为自己的下级';
                        }
                        array_push($levelsArr, $this->data['parent_id']);
                    } else {
                        $this->error = '上级组织不存在';
                    }
                }
                $levelsArr = array_unique($levelsArr);
                $this->data['levels'] = implode(',', $levelsArr);
            }
        }

        return parent::after_validate(); // TODO: Change the autogenerated stub
    }
}
